package cn.tl.hrm.service.impl;

import cn.tl.hrm.doc.CourseDoc;
import cn.tl.hrm.dto.CourseSearchParamDTO;
import cn.tl.hrm.mapper.HighlightResultMapper;
import cn.tl.hrm.repository.CourseElasticSearchRepository;
import cn.tl.hrm.service.ICourseElasticSearchService;
import cn.tl.hrm.util.PageList;
import cn.tl.hrm.vo.AggPageListVO;
import cn.tl.hrm.vo.Bucket;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseElasticSearchServiceImpl implements ICourseElasticSearchService {

    @Autowired
    private CourseElasticSearchRepository repository;

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public void add(CourseDoc doc) {
        repository.save(doc);
    }

    @Override
    public PageList<CourseDoc> searchCourse(CourseSearchParamDTO dto) {

        //查询对象的建造者
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //分页=============================================================
        builder.withPageable(PageRequest.of(dto.getPage() - 1,dto.getRows()));
        //排序=============================================================
        if(StringUtils.isNotEmpty(dto.getSortField())){

            String sortField = "onlineTime";
            switch (dto.getSortField()){
                case "xl": sortField = "saleCount";break;
                case "xp": sortField = "onlineTime";break;
                case "jg": sortField = "price";break;
                case "rq": sortField = "viewCount";break;
                case "pl": sortField = "commentCount";break;
            }
            SortOrder sortOrder = SortOrder.DESC;
            if(StringUtils.isNotEmpty(dto.getSortType())
                    && dto.getSortType().equalsIgnoreCase("asc")){
                sortOrder = SortOrder.ASC;
            }

            builder.withSort(new FieldSortBuilder(sortField).order(sortOrder));
        }
        //查询条件==========================================================
        //================================================================
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //DSL查询----------------------------------------------------------
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
        }

        //DSL过滤----------------------------------------------------------
        if(null != dto.getCourseTypeId()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
        if(StringUtils.isNotEmpty(dto.getGradeName())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("gradeName",dto.getGradeName()));
        }
        if(dto.getPriceMax() != null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }
        if(dto.getPriceMin() != null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin() ));
        }
        if(StringUtils.isNotEmpty(dto.getTenantName())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("tenantName",dto.getTenantName()));
        }

        builder.withQuery(boolQueryBuilder);

        //处理高亮=======================================================
        HighlightBuilder.Field hightLightField = new HighlightBuilder.Field("name")
                .preTags("<font style='color:red;font-size:17px' >")
                .postTags("</font>");
        builder.withHighlightFields(hightLightField);

        //处理高亮=======================================================
        //机构terms的聚合
        TermsAggregationBuilder tenantAgg = AggregationBuilders
                .terms("tenantAgg").field("tenantName");
        //等级的terms的聚合
        TermsAggregationBuilder gradeAgg = AggregationBuilders
                .terms("gradeAgg").field("gradeName");

        builder.addAggregation(tenantAgg).addAggregation(gradeAgg);

        //创建查询对象=======================================================
        SearchQuery searchQuery = builder.build();
        //执行搜索
        //Page<CourseDoc> page = repository.search(searchQuery);
        AggregatedPage<CourseDoc> page = template.queryForPage(searchQuery , CourseDoc.class , highlightResultMapper);
        //处理聚合结果----------------------------------
        Aggregations aggregations = page.getAggregations();
        //Map的key =  tenantNameAgg  :
        Map<String, Aggregation> aggregationMap = aggregations.asMap();

        //封装聚合结果
        Map<String, List<Bucket>> aggs = new HashMap<>();

        System.out.println("=====================================================");
        aggregationMap.entrySet().forEach(entry->{
            //聚合的名字
            String aggName = entry.getKey();
            //结果列表
            List<Bucket> bucketsResult = new ArrayList<>();
            System.out.println("聚合的名字："+aggName);
            //聚合对象
            ParsedStringTerms aggregation = (ParsedStringTerms) entry.getValue();
            List<? extends Terms.Bucket> buckets = aggregation.getBuckets();
            buckets.forEach(bucket -> {
                String key = bucket.getKeyAsString();
                long docCount = bucket.getDocCount();
                System.out.println("bucket的key = "+key +" docCount = "+docCount);

                bucketsResult.add(new Bucket(key , docCount));
            });
            aggs.put(aggName,bucketsResult);

        });
        //把结果封装到PageList
        return new AggPageListVO(page.getTotalElements() , page.getContent() , aggs);
    }
}
